package com.jd.finance.core.controller.api;


import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jd.finance.core.config.URLConst;
import com.jd.finance.core.mapper.ProductMapper;
import com.jd.finance.core.pojo.dto.GetOverDueDTO;
import com.jd.finance.core.pojo.dto.GetRepayRecordDTO;
import com.jd.finance.core.pojo.entity.Product;
import com.jd.finance.core.pojo.entity.User;
import com.jd.finance.core.pojo.request.UserRegisterRequest;
import com.jd.finance.core.service.BankCardService;
import com.jd.finance.core.service.LoanApplyService;
import com.jd.finance.core.service.LoanService;
import com.jd.finance.core.service.UserService;
import com.jd.finance.result.BaseResult;
import com.jd.finance.util.HttpUtils;
import com.jd.finance.util.JwtUtils;
import com.jd.finance.util.RegexValidateUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author LiQingBo
 * @since 2022-05-17
 */
@Api(tags = "用户中心")
@Slf4j
@RestController
@RequestMapping("/api/core/userCenter")
public class UserController {

    @Resource
    private UserService userService;
    @Resource
    private LoanService loanService;
    @Resource
    private BankCardService bankcardService;
    @Resource
    private ProductMapper productMapper;
    @Resource
    private LoanApplyService loanApplyService;

    @ApiOperation("注册")
    @PostMapping("register")
    public BaseResult register(UserRegisterRequest userRegisterRequest) {
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        if (StringUtils.isAllBlank(userAccount, userPassword, checkPassword)) {
            log.error("注册信息为空！");
            return BaseResult.error().message("注册信息为空");
        }
        return userService.userRegister(userAccount, userPassword, checkPassword);
    }

    @ApiOperation("登录")
    @GetMapping("/login")
    public BaseResult login(String userAccount, String userPassword, HttpServletRequest request) {
        if (StringUtils.isAllBlank(userAccount,userPassword)) {
            log.error("登录信息为空！");
            return BaseResult.error().message("登录信息为空");
        }
        return userService.userLogin(userAccount,userPassword,request);
    }

    @ApiOperation("个人实名认证")
    @PostMapping("/userCertifica")
    public BaseResult userCertifica(User user) {
        String idNo = user.getIdNo();
        String userName = user.getUserName();
        String userPhone = user.getUserPhone();
        Integer uid = user.getUid();
        if (StringUtils.isAllBlank(idNo, userName, userPhone, String.valueOf(uid))) {
            log.error("个人实名认证信息为空！");
            return BaseResult.error().message("信息为空");
        }
        return userService.userCertifica(idNo, userName, userPhone, uid);
    }

    @ApiOperation("查询个人是否实名认证")
    @PostMapping("/getUserCertifica")
    public BaseResult getUserCertifica(Integer uid) {
        if (uid == null) {
            log.error("用户id为空！");
            return BaseResult.error().message("用户id为空!");
        }
        return userService.getUserCertifica(uid);
    }

    @ApiOperation("查询审核通过，待签约的产品")
    @GetMapping("/getExamPassed")
    public BaseResult getExamPassed(Integer uid) {
        boolean blank = StringUtils.isBlank(String.valueOf(uid));
        System.out.println(blank);
        if (uid == null) {
            log.error("查询审核通过，待签约的产品,信息为空！controller");
            return BaseResult.error().message("信息为空");
        }
        return loanService.getExamPassed(uid);
    }

    @ApiOperation("查询个人信息")
    @GetMapping("/getUserInfo")
    public BaseResult getUserInfo(Integer uid) {
        //判断是否为空
        if (StringUtils.isBlank(String.valueOf(uid))) {
            log.error("用户id为空！");
            return BaseResult.error().message("用户信息id为空");
        }
        return userService.getUserInfo(uid);
    }


    @ApiOperation("修改密码，联系电话")
    @PostMapping("/updateInfo")
    public BaseResult updateInfo(Integer uid, String userPassword, String userPhone) {

        if (uid == null) {
            log.error("用户输入信息为空！");
            return BaseResult.error().message("用户输入信息为空");
        }
        if (!StringUtils.isAllBlank(userPassword, userPhone)) {
            log.error("用户输入信息为空！");
            return BaseResult.error().message("用户输入信息为空");
        }
        //使用工具类检查手机号码,密码
        if (!RegexValidateUtils.checkCellphone(userPhone)) {
            log.error("手机号信息有误！");
            return BaseResult.error().message("手机号信息有误");
        }
        return userService.updateInfo(uid, userPassword, userPhone);



    }

    @ApiOperation("根据uid查询还款记录")
    @GetMapping("/getRepayRecord")
    public BaseResult getRepayRecord(Integer uid) {
        if (uid == null) {
            log.error("用户信息为空！");
            return BaseResult.error().message("用户信息为空");
        }
        User user = userService.getRepayInfo(uid);
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("idNo", user.getIdNo());
        //封装post参数
        StringBuilder postData = new StringBuilder();
        for (Map.Entry<String, Object> param : paramMap.entrySet()) {
            postData.append(param.getKey()).append("=").append(param.getValue()).append("&");
        }
        log.info(String.format("--> 发送请求到web：post data %1s", postData));
        byte[] bytes1 = postData.toString().getBytes(StandardCharsets.UTF_8);
        byte[] result = HttpUtils.doPost(URLConst.GET_USER_REPAY_INFO_URL, bytes1);
        String s = new String(result);
        log.info(String.format("--> web应答结果：result data %1s", s));
        List<GetRepayRecordDTO> overDueList = JSONArray.parseArray(s, GetRepayRecordDTO.class);

        return BaseResult.ok().data("data", overDueList);
    }

    @ApiOperation("根据uid查询银行卡信息")
    @GetMapping("/getCardInfo")
    public BaseResult getCardInfo(Integer uid) {
        if (uid == null) {
            log.error("查询银行卡信息为空！");
            return BaseResult.error().message("信息为空");
        }
        return bankcardService.getCardInfo(uid);
    }

    @ApiOperation("查询平台交易额")
    @GetMapping("/getTradeAmount")
    public BaseResult getTradeAmount() {
        BigDecimal count = loanService.findDealCount();
        if (count == null) {
            log.error("交易额为0");
            return BaseResult.ok().data("jiaoyiCount：", 0);
        }
        return BaseResult.ok().data("jiaoyiCount：", count);
    }


    @ApiOperation("根据uid查询  个人逾期产品记录")
    @GetMapping("/getUserOverDue/{uid}")
    public BaseResult getOverDue(@PathVariable("uid") Integer uid) {
        if (uid == null) {
            log.error("uid为空");
            return BaseResult.error().message("uid为空");
        }

        User user = userService.getUserInfoS(uid);
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("idNo", user.getIdNo());
        //封装post参数 到路径
        StringBuilder postData = new StringBuilder();
        for (Map.Entry<String, Object> param : paramMap.entrySet()) {
            postData.append(param.getKey()).append("=").append(param.getValue()).append("&");
        }
        log.info(String.format("--> 发送请求到web：post data %1s", postData));
        byte[] bytes1 = postData.toString().getBytes(StandardCharsets.UTF_8);
        byte[] result = HttpUtils.doPost(URLConst.GET_OVER_USER_URL, bytes1);
        String s = new String(result);
        List<GetOverDueDTO> overDueList = JSONArray.parseArray(s, GetOverDueDTO.class);
        for (GetOverDueDTO getOverDueDTO : overDueList) {
            String proName = getOverDueDTO.getCpName();
            QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("pro_name", proName);
            Product product = productMapper.selectOne(queryWrapper);
            getOverDueDTO.setPid(product.getPid());
        }
        log.info(String.format("--> web应答结果：result data %1s", overDueList));
        return BaseResult.ok().data("data", overDueList);
    }

    @ApiOperation("根据uid查询  个人完整信息")
    @GetMapping("/getUserInfoS/{uid}")
    public User getUserInfoS(@PathVariable("uid") Integer uid) {
        if (uid == null) {
            log.error("uid为空");
            return null;
        }

        User user = userService.getUserInfoS(uid);
        return user;
    }

    @ApiOperation("贷款申请（贷款银行id，产品id，个人身份证号或企业法人身份证号，开户人（必须和企业法人身份证号一致），卡号，开用户整体负债）")
    @PostMapping("/applyLoan")
    public BaseResult applyLoan(Integer bid, Integer proId, Integer workId, String no,
                                String userName, String loanReason, String cardNum, BigDecimal allDebt) {
        if (bid == null || proId == null || workId == null) {
            log.error("传入参数为空");
            return BaseResult.error().message("传入参数为空");
        }
        if (StringUtils.isAllBlank(userName, loanReason, cardNum, no)) {
            log.error("传入参数为空");
            return BaseResult.error().message("传入参数为空");
        }
        if (allDebt == null) {
            log.error("传入参数为空");
            return BaseResult.error().message("传入参数为空");
        }
        return loanApplyService.applyLoan(bid, proId, workId, no, userName, loanReason, cardNum, allDebt);
    }

    @ApiOperation("扫码登录")
    @GetMapping("/scanCode")
    public BaseResult scanCode(Integer uid) {
        if (uid == null) {
            log.error("扫码登录，uid为空!");
            return BaseResult.error().message("扫码登录，uid为空!");
        }

        return userService.scanCode(uid);
    }

}

